package service

import (
	"github.com/zoumo/goset"
	"gorm.io/gorm"
	"guns-go/global"
	"guns-go/model"
	"guns-go/model/request"
	"strconv"
)

func GetUserDataScopes(userId int, orgId int) (err error, ids []int) {

	userDataScopeIdSlice := make([]int, 0)

	if userId != 0 && orgId != 0 {

		//获取该用户对应的数据范围集合
		err, scopeIds := GetUserDataScopeIdSlice(userId)

		if err != nil {
			return err, nil
		}

		//获取该用户的角色对应的数据范围集合
		err, roleScopeIds := GetUserRoleDataScopeIdList(userId, orgId)

		if err != nil {
			return err, nil
		}

		userDataScopeIdSlice = append(userDataScopeIdSlice, scopeIds...)
		userDataScopeIdSlice = append(roleScopeIds, scopeIds...)

		pSet := goset.NewSafeSetFromInts(userDataScopeIdSlice)

		userDataScopeIdSlice = userDataScopeIdSlice[:0]

		userDataScopeIdSlice = append(userDataScopeIdSlice, pSet.ToInts()...)
	}

	return err, userDataScopeIdSlice
}

func GetUserDataScopeIdSlice(userId int) (err error, scopeIds []int) {

	var userDataScopes []model.SysUserDataScope
	err = global.GVA_DB.Where("user_id = ?", userId).Find(&userDataScopes).Error

	if err != nil {
		return err, nil
	}

	if len(userDataScopes) > 0 {

		dataScopeIds := make([]int, 0)

		for _, dataScope := range userDataScopes {
			dataScopeIds = append(dataScopeIds, dataScope.OrgId)
		}
		return err, dataScopeIds
	}
	return err, nil
}

func DeleteUserDataScopeListByUserId(userId int, tx *gorm.DB) error {

	err := tx.Delete(model.SysUserDataScope{}, "user_id = ?", userId).Error
	return err
}

func DeleteUserDataScopeByIds(ids []int) error {
	return global.GVA_DB.Delete(model.SysUserDataScope{}, "id in (?)", ids).Error
}

func SaveUserDataScope(userDataScope *model.SysUserDataScope, tx *gorm.DB) error {

	err := tx.Create(userDataScope).Error
	return err
}

func SysUserGrantData(sysUserParam *request.SysUserParam) error {

	userId := sysUserParam.Id

	tx := global.GVA_DB.Begin()

	//删除所拥有数据
	err := DeleteUserDataScopeListByUserId(userId, tx)

	if err != nil {
		tx.Rollback()
		return err
	}

	//授权数据
	for _, orgId := range sysUserParam.GrantOrgIdList {

		sysUserDataScope := new(model.SysUserDataScope)

		sysUserDataScope.UserId = userId
		orgIdInt, _ := strconv.Atoi(orgId)
		sysUserDataScope.OrgId = orgIdInt

		err = SaveUserDataScope(sysUserDataScope, tx)

		if err != nil {
			tx.Rollback()
			return err
		}
	}
	tx.Commit()
	return nil
}

//根据机构id集合删除对应的用户-数据范围关联信息
func DeleteUserDataScopeListByOrgIdList(orgIdList []int, tx *gorm.DB) error {
	return tx.Delete(model.SysUserDataScope{}, "org_id in (?)", orgIdList).Error
}
